package com.xtool.livewallpaper.base

import android.content.SharedPreferences
import com.tencent.mmkv.MMKV
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

inline fun <reified T> MMKV.delegate(
    key: String,
    defaultValue: T,
    crossinline setter: MMKV.(String, T) -> SharedPreferences.Editor,
    crossinline getter: MMKV.(String, T) -> T?
) = object : ReadWriteProperty<Any, T> {
    override fun getValue(thisRef: Any, property: KProperty<*>): T {
        return getter(key, defaultValue) ?: defaultValue
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
        setter(key, value).apply()
    }
}

fun MMKV.boolean(key: String, defaultValue: Boolean): ReadWriteProperty<Any, Boolean> {
    return delegate(key, defaultValue, MMKV::putBoolean, MMKV::decodeBool)
}

fun MMKV.string(key: String, defaultValue: String): ReadWriteProperty<Any, String> {
    return delegate(key, defaultValue, MMKV::putString, MMKV::decodeString)
}

fun MMKV.int(key: String, defaultValue: Int): ReadWriteProperty<Any, Int> {
    return delegate(key, defaultValue, MMKV::putInt, MMKV::decodeInt)
}

fun MMKV.long(key: String, defaultValue: Long): ReadWriteProperty<Any, Long> {
    return delegate(key, defaultValue, MMKV::putLong, MMKV::decodeLong)
}

fun MMKV.float(key: String, defaultValue: Float): ReadWriteProperty<Any, Float> {
    return delegate(key, defaultValue, MMKV::putFloat, MMKV::decodeFloat)
}

fun MMKV.stringSet(key: String, defaultValue: Set<String>): ReadWriteProperty<Any, Set<String>> {
    return delegate(key, defaultValue, MMKV::putStringSet, MMKV::decodeStringSet)
}